#!/bin/sh

source "{{ m_install }}/.deploy-meza/config.sh"

if [ -z "$1" ]; then
	do_wikis="*/"
else
	do_wikis="$1"
fi

wiki_dir="{{ m_htdocs }}/wikis"

cd "$wiki_dir"
for d in $do_wikis; do

	if [ -z "$1" ]; then
		wiki_id=${d%/}
	else
		wiki_id="$d"
	fi

	if [ ! -d "$wiki_dir/$wiki_id" ]; then
		echo "\"$wiki_id\" not a valid wiki ID"
		continue
	fi

	timestamp=$(date +"%F_%T")
	exception_log="{{ m_logs }}/smw-rebuilddata-exceptions-$wiki_id-$timestamp.log"
	out_log="{{ m_logs }}/smw-rebuilddata/$wiki_id.$timestamp.log"

	echo "Start rebuilding SMW data for \"$wiki_id\" at $timestamp"
	echo "  Exception log (if req'd):"
	echo "    $exception_log"
	echo "  Output log:"
	echo "    $out_log"

	start_id_file="{{ m_logs }}/custom-rebuild-start-id-file"

	# on the first pass, use -f to fully rebuild the SMW structure
	dependent_option="-f"

	# Initialize start ID file to ID=0
	echo "0" > "$start_id_file"
	start_id=$(cat "$start_id_file")


	while [ "$start_id" != "-1" ]; do

		previous_start_id="$start_id"

		WIKI="$wiki_id" \
		php "{{ m_mediawiki }}/extensions/SemanticMediaWiki/maintenance/rebuildData.php" \
		-d 5 -v $dependent_option --ignore-exceptions \
		--debug \
		--report-runtime \
		--startidfile "$start_id_file" -n 1000 \
		--exception-log="$exception_log" \
		>> "$out_log" 2>&1

		# Set a new start id
		start_id=$(cat "$start_id_file")

		# If something happens to prevent start_id from incrementing, manually increment it.
		if [ "$previous_start_id" = "$start_id" ]; then
			last_id_logged=$(grep "... updating" "$out_log" | tail -1 | awk '{print $3}')
			next_id=$((last_id_logged+1))
			echo "Start ID not updating. Was $start_id. Last ID logged = $last_id_logged. Incrementing to $next_id" >> "$exception_log"
			start_id="$next_id"
		fi

		# after first run, don't rebuild structure, but do skip rebuilding properties
		dependent_option="--skip-properties"

		echo "next pass start id = $start_id"
		echo "$(date +"%F_%T")"

		echo "next pass start id = $start_id" >> "$out_log"
		echo "$(date +"%F_%T")" >> "$out_log"

	done


	# If the above command had a failing exit code
	if [[ $? -ne 0 ]]; then

		endtimestamp=$(date +"%F_%T")

		# FIXME #577 #681: add notification/warning system here
		echo "rebuildData FAILED for \"$wiki_id\" at $endtimestamp"

	#if the above command had a passing exit code (e.g. zero)
	else
		endtimestamp=$(date +"%F_%T")

		echo "rebuildData completed for \"$wiki_id\" at $endtimestamp"
	fi

done
